<?php
$tokenDir = '../fastphp/token';
if (!is_dir($tokenDir)) {
    mkdir($tokenDir);
}
$installed = $tokenDir . '/installed.txt';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // 获取请求的原始输入数据
    $json = file_get_contents('php://input');

    // 检查输入是否为有效的JSON字符串
    $data = json_decode($json, true); // 将JSON字符串解析为关联数组
    if (json_last_error() === JSON_ERROR_NONE) {
        try {
            // 处理解析后的数据
            $dbName = $data['dbName'];
            $dbHost = $data['dbHost'];
            $dbPort = $data['dbPort'];
            $dbUserName = $data['dbUserName'];
            $dbUserPwd = $data['dbUserPwd'];
            $dbTableFre = $data['dbTableFre'];
            $dsn = "mysql:host=$dbHost;dbname=$dbName;port=$dbPort";
            $pdo = new PDO($dsn, $dbUserName, $dbUserPwd);
            // 设置错误模式为异常
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // 读取SQL文件内容
            $sqlFile1 = '../tpl/admin_menus.sql';
            $sqlFile2 = '../tpl/admin_user.sql';
            $sqlContent1 = file_get_contents($sqlFile1);
            $sqlContent2 = file_get_contents($sqlFile2);
            $sqlContent1 = str_replace('prefix', $dbTableFre, $sqlContent1);
            $sqlContent2 = str_replace('prefix', $dbTableFre, $sqlContent2);

            // 分割SQL语句（这里是一个简单的分割方法，可能不适用于所有情况）
            $sqlStatements1 = explode(';', preg_replace("/\s*;\s*/", ";", trim($sqlContent1)));
            $sqlStatements2 = explode(';', preg_replace("/\s*;\s*/", ";", trim($sqlContent2)));

            // 逐个执行SQL语句
            foreach ($sqlStatements1 as $statement) {
                $trimmedStatement = trim($statement);
                if (!empty($trimmedStatement)) {
                    $pdo->exec($trimmedStatement);
                }
            }
            foreach ($sqlStatements2 as $statement) {
                $trimmedStatement = trim($statement);
                if (!empty($trimmedStatement)) {
                    $pdo->exec($trimmedStatement);
                }
            }

            $config = '../tpl/config.php';
            $configContent = file_get_contents($config);
            $configContent = str_replace('dbName', $dbName, $configContent);
            $configContent = str_replace('dbUserName', $dbUserName, $configContent);
            $configContent = str_replace('dbUserPwd', $dbUserPwd, $configContent);
            $configContent = str_replace('dbHost', $dbHost, $configContent);
            $configContent = str_replace('dbPort', $dbPort, $configContent);
            $configContent = str_replace('dbTablePre', $dbTableFre, $configContent);

            if (!is_dir('../config')) {
                mkdir('../config');
            }
            $fp = fopen('../config/config.php', 'w');
            fwrite($fp, $configContent);
            fclose($fp);

            $baseAdd = '../tpl/baseAdd.tpl';
            $baseAddContent = file_get_contents($baseAdd);
            $baseAddContent = str_replace('dbName', $dbName, $baseAddContent);

            $fp = fopen('../application/views/AdminMenu/baseAdd.tpl', 'w');
            fwrite($fp, $baseAddContent);
            fclose($fp);

            $fp = fopen($installed, 'w');
            fwrite($fp, '1');
            fclose($fp);

            echo json_encode([
                'code' => 200,
                'msg' => '成功'
            ]);
            exit();
        } catch (PDOException $e) {
            echo json_encode([
                'code' => 400,
                'msg' => '连接失败: ' . $e->getMessage()
            ]);
            exit();
        }
    }
} else {
    if (is_file($installed)) {
        header('Location: index.php');
        exit();
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>初始化</title>
    <link rel="stylesheet" href="./static/layui/css/layui.css" media="all">
    <style>
        .main {
            width: 400px;
            margin: 10% auto;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header img {
            width: 80px;
            height: 80px;
        }

        .header p {
            margin-top: 20px;
            font-size: 24px;
        }

        .login-form > .layui-form-item {
            position: relative;
        }

        .user-login {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
        }
    </style>
</head>
<body>
<div class="main">
    <form class="layui-form login-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">数据库名</label>
            <div class="layui-input-inline">
                <input
                        type="text"
                        name="dbName"
                        required
                        lay-verify="required"
                        placeholder="请输入数据库名"
                        autocomplete="off"
                        class="layui-input"
                />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">数据库地址</label>
            <div class="layui-input-inline">
                <input
                        type="text"
                        name="dbHost"
                        required
                        lay-verify="required"
                        placeholder="请输入数据库地址"
                        autocomplete="off"
                        class="layui-input"
                        value="localhost"
                />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">数据库端口号</label>
            <div class="layui-input-inline">
                <input
                        type="number"
                        name="dbPort"
                        required
                        lay-verify="required"
                        placeholder="请输入数据库端口号"
                        autocomplete="off"
                        class="layui-input"
                        value="3306"
                />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">数据库用户名</label>
            <div class="layui-input-inline">
                <input
                        type="text"
                        name="dbUserName"
                        required
                        lay-verify="required"
                        placeholder="请输入数据库用户名"
                        autocomplete="off"
                        class="layui-input"
                        value="root"
                />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">数据库用户密码</label>
            <div class="layui-input-inline">
                <input
                        type="password"
                        name="dbUserPwd"
                        required
                        lay-verify="required"
                        placeholder="请输入数据库用户密码"
                        autocomplete="off"
                        class="layui-input"
                />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">表名前缀</label>
            <div class="layui-input-inline">
                <input
                        type="text"
                        name="dbTableFre"
                        required
                        lay-verify="required"
                        placeholder="请输入数据库端口号"
                        autocomplete="off"
                        class="layui-input"
                        value="tp_"
                />
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">
                    立即提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary">
                    重置
                </button>
            </div>
        </div>
    </form>
</div>

<script src="./static/layui/layui.js" charset="utf-8"></script>
<script>
    //Demo
    layui.use("form", function () {
        var form = layui.form;
        $ = layui.jquery
        //提交
        form.on("submit(formDemo)", function (data) {
            // layer.msg(JSON.stringify(data.field));
            $.post('./install.php', JSON.stringify(data.field), function (res) {
                if (res.code === 200) {
                    window.location.href = './index.php/admin/user/login'
                } else {
                    layer.msg('初始化失败')
                }
            }, 'json')
            return false;
        });
    });
</script>
</body>
</html>

